import { memo, useEffect, useState, useRef } from 'react'
import { Chart } from '@antv/g2'

const initialData = [
  { year: '1991', value: 15468 },
  { year: '1992', value: 16100 },
  { year: '1993', value: 15900 },
  { year: '1994', value: 17409 },
  { year: '1995', value: 17000 },
  { year: '1996', value: 31056 },
  { year: '1997', value: 31982 },
  { year: '1998', value: 32040 },
  { year: '1999', value: 33233 }
]

function AreaChart() {
  const containerRef = useRef(null)
  const chartRef = useRef(null)
  const dataRef = useRef([...initialData])
  const yearCounter = useRef(2000)

  useEffect(() => {
    // 1. 创建图表实例
    const chart = new Chart({
      container: containerRef.current,
      autoFit: true,
      height: 500,
      padding: [40, 40, 60, 60]
    })
    chartRef.current = chart

    // 2. 载入初始数据
    chart.data(dataRef.current)

    // 3. 配置坐标
    chart.scale({
      year: { type: 'cat', alias: '年份', tickInterval: 1 },
      value: { alias: '数值', nice: true }
    })

    // 4. 绘制面积和折线
    chart.area().position('year*value').shape('smooth').style({ fillOpacity: 0.2 })
    chart.line().position('year*value').shape('smooth').style({ strokeWidth: 2 })

    // 5. 美化坐标轴和 tooltip
    chart.axis('year', { title: null })
    chart.axis('value', {
      title: null,
      labelFormatter: (v) => `${(+v / 1000).toFixed(0)}k`
    })
    chart.tooltip({ showCrosshairs: true, shared: true })

    // 6. 渲染
    chart.render()

    // 7. 启动定时器模拟动态数据更新
    const timer = setInterval(() => {
      const newPoint = {
        year: String(yearCounter.current++),
        value: Math.round(15000 + Math.random() * 20000)
      }
      const d = dataRef.current
      d.push(newPoint)
      if (d.length > 20) d.shift()
      chart.changeData(d)
    }, 1000)

    // 清理
    return () => {
      clearInterval(timer)
      chart.destroy()
    }
  }, [])

  return <div ref={containerRef} />
}

export default memo(AreaChart)
